package net.wisedream.littletools.jff.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * HttpClient工具类
 *
 * @author pseudo
 * @Created Feb 14, 2014
 */
public class HttpClientHelper {
	public static void shutdown(HttpClient httpClient) {
		httpClient.getConnectionManager().shutdown();
	}

	/**
	 * 设置httpclient默认代理
	 * 
	 * @param proxy
	 *            格式 127.0.0.1:8080
	 */
	public static void setProxy(HttpClient httpClient, String proxy) {
		if (proxy != null) {
			String[] tmp = proxy.split(":");
			HttpHost proxyHost = new HttpHost(tmp[0], Integer.valueOf(tmp[1]));
			httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
					proxyHost);
		} else {
			httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
					null);
		}
	}

	public static String getProxy(HttpClient httpClient) {
		HttpHost proxyHost = (HttpHost) httpClient.getParams().getParameter(
				ConnRouteParams.DEFAULT_PROXY);
		if (proxyHost == null)
			return null;
		return proxyHost.getHostName() + ":" + proxyHost.getPort();
	}

	public static HttpResponse execute(HttpClient httpClient,
			HttpUriRequest request, String tmpProxy) throws Exception {
		Object origProxy = httpClient.getParams().getParameter(
				ConnRouteParams.DEFAULT_PROXY);
		// 设置临时代理
		setProxy(httpClient, tmpProxy);
		try {
			return httpClient.execute(request);
		} catch (Exception e) {
			throw e;
		} finally {
			// 恢复代理
			httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
					origProxy);
		}
	}

	public static String readContent(HttpResponse resp, String defaultCharset)
			throws IOException {
		HttpEntity entity = resp.getEntity();
		String charset = getCharset(entity, defaultCharset);
		String content = null;
		if (resp.containsHeader("Content-Encoding")
				&& resp.getHeaders("Content-Encoding")[0].getValue().equals(
						"gzip"))
			content = gzipDecompress(entity.getContent(), charset);
		else
			content = EntityUtils.toString(entity, charset);
		return content;
	}

	/**
	 * 读取压缩数据
	 * 
	 * @param entity
	 * @param charset
	 * @return
	 * @throws IOException
	 */
	private static String gzipDecompress(InputStream in, String charset)
			throws IOException {
		// 解压
		GZIPInputStream gzipIn = new GZIPInputStream(in);
		byte[] buffer = new byte[512];
		int count = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((count = gzipIn.read(buffer)) > -1) {
			bos.write(buffer, 0, count);
		}
		bos.flush();
		bos.close();

		return bos.toString(charset);

	}

	/**
	 * 从响应实体中取得字符编码
	 * 
	 * @param entity
	 * @param defaultCharset
	 * @return
	 */
	public static String getCharset(HttpEntity entity, String defaultCharset) {
		String charset = defaultCharset;
		try {
			charset = ContentType.get(entity).getCharset().name();
		} catch (Exception e) {
		}
		return charset;
	}

	/**
	 * 是否自动跳转
	 * 
	 * @param flag
	 */
	public static void setFollowRedirect(HttpClient httpClient, boolean flag) {
		HttpClientParams.setRedirecting(httpClient.getParams(), flag);
	}

	/**
	 * 清理cookie
	 */
	public static void clearCookie(AbstractHttpClient httpClient) {
		httpClient.getCookieStore().clear();
	}

	public static List<Cookie> getCookie(AbstractHttpClient httpClient) {
		return httpClient.getCookieStore().getCookies();
	}
}
